//
//  JsonAndStringMethod.swift
//  AispeechMobileApp
//
//  Created by Lee on 2019/2/25.
//  Copyright © 2019年 Lee. All rights reserved.
//

import Foundation

class JsonAndStringMethod:NSObject {
    
    //MARK: - 字典转json字符串
    func getJSONStringFromDictionary(dictionary:NSDictionary) -> String {
        
        if (!JSONSerialization.isValidJSONObject(dictionary)) {
            print(message: "无法解析出JSONString")
            return ""
        }
        let data : NSData! = try? JSONSerialization.data(withJSONObject: dictionary, options: []) as NSData
        let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
//        print(message: JSONString)
        return JSONString! as String
    }
    
    //MARK: - 数组转json字符串
    func getJSONStringFromArray(array:NSArray) -> String {
        
        if (!JSONSerialization.isValidJSONObject(array)) {
            print("无法解析出JSONString")
            return ""
        }
        let data : NSData! = try? JSONSerialization.data(withJSONObject: array, options: []) as NSData
        let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
        return JSONString! as String
    }
    
    //MARK: - JSON字符串转化为字典
    func getDictionaryFromJSONString(jsonString:String) -> NSDictionary {
        
        let jsonData:Data = jsonString.data(using: .utf8)!
        
        let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
        if dict != nil {
            return dict as! NSDictionary
        }
        return NSDictionary()
    }
    
    //MARK: - JSON字符串转化为数组
    func getArrayFromJSONString(jsonString:String) ->NSArray{
        
        let jsonData:Data = jsonString.data(using: .utf8)!
        
        let array = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
        if array != nil {
            return array as! NSArray
        }
        return array as! NSArray
    }
    
    //MARK: - 读取本地json文件
    func readLocalJsonFileWithName(name:String) -> Any? {
        
        let path = Bundle.main.path(forResource: name, ofType: "json")
        let url = URL(fileURLWithPath: path!)
        // 带throws的方法需要抛异常
        do {
            /*
             * try 和 try! 的区别
             * try 发生异常会跳到catch代码中
             * try! 发生异常程序会直接crash
             */
            let data = try Data(contentsOf: url)
            let jsonData:Any = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)
            return jsonData
        } catch let error as Error? {
            print("读取本地数据出现错误!",error!)
            return nil
        }
    }

}


